import models

from django import forms
from django.forms.models import inlineformset_factory, modelformset_factory
from django.contrib.auth.models import User

class CaipsRequestForm(forms.Form):
    email = forms.EmailField()
    file_no = forms.CharField(max_length=15,)
    first_name = forms.CharField(max_length=45)
    last_name = forms.CharField(max_length=45)
    birthdate = forms.DateField()

    office_name = forms.ModelChoiceField(queryset=models.VisaOffice.objects.all(),
                                         empty_label=u'Please select')

    #middle_name = forms.CharField(max_length=45)
    #client_id = forms.CharField(max_length=45)

class CaipsRequestPaymentForm(forms.ModelForm):
    class Meta:
        model = models.CaipsRequest
        fields = ('file_no', 'visa_office', 'email')

class ConsentForm(forms.ModelForm):
    class Meta:
        model = models.ConsentForm
        exclude = ('middle_name', 'is_principal')

ConsentFormSet = inlineformset_factory(models.CaipsRequest, models.ConsentForm,
                                       exclude = ('middle_name'), 
                                       extra=0, can_delete=False)

class InitialServiceRequestForm(forms.Form):
    email = forms.EmailField()
    file_no = forms.CharField(max_length=15)
    visa_office = forms.ModelChoiceField(queryset=models.VisaOffice.objects.all(),
                                         label=u'Visa office name',
                                         empty_label=u'Please select')

attrs_dict = {'class': 'required'}

class InitialServiceRequestFormUserCreate(InitialServiceRequestForm):
    create_account = forms.BooleanField()
    username = forms.RegexField(regex=r'^[\w.@+-]+$',
                                max_length=30,
                                widget=forms.TextInput(attrs=attrs_dict),
                                label=u'Username',
                                error_messages={'invalid': u'This value must contain only letters, numbers and underscores.'})
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                                label=u'Password')
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                                label=u'Password (again)') 

    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already
        in use.
        
        """
        try:
            user = User.objects.get(username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(u'A user with that username already exists.')

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.
        
        """
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(u'The two password fields did not match.')
        return self.cleaned_data

class ServiceRequestPaymentForm(forms.ModelForm):
    class Meta:
        model = models.ServiceRequest
        fields = ('email', 'file_no', 'visa_office', 'amount_paid', )

class ApplicantForm(forms.ModelForm):
    class Meta:
        model = models.Applicant
        exclude = ('middle_name', 'is_principal',)

class ApplicantFormInitial(forms.ModelForm):
    class Meta:
        model = models.Applicant
        fields = ('first_name', 'last_name', 'birthdate',)

ApplicantFormInitialFormSet = modelformset_factory(models.Applicant,
                                                   fields = ('first_name', 'last_name', 'birthdate',),
                                                   extra=0, can_delete=False)

ApplicantFormFormSet = inlineformset_factory(models.ServiceRequest, models.Applicant,
                                                    fields = ('first_name', 'last_name', 'birthdate',),
                                                    extra=0, can_delete=False)

class ApplicantFormConsent(forms.ModelForm):
    class Meta:
        model = models.Applicant
        fields = ('first_name', 'last_name', 'birthdate', 'consent_form')

ApplicantFormConsentFormSet = inlineformset_factory(models.ServiceRequest, models.Applicant,
                                       exclude = ('middle_name'), 
                                       extra=0, can_delete=False)
